using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using ComputerShopE3.Models;

namespace ComputerShopE3.Controllers
{
    public class GradeController : Controller
    {
        //
        // GET: /Grade/
        ComputerShopDBEntities1 _db = new ComputerShopDBEntities1();

        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Grade/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Grade/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Grade/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(int id, FormCollection form)
        {
            try
            {
                // TODO: Add insert logic here
                short Diem = short.Parse(form.Get("Diem"));

                SAN_PHAM sp = _db.SAN_PHAM.Where((c) => c.id == id).FirstOrDefault();
                NGUOI_DUNG nd = _db.NGUOI_DUNG.Where((c) => c.TenDangNhap == User.Identity.Name).FirstOrDefault();

                DANH_GIA dg = new DANH_GIA
                {
                    Diem = Diem,
                    SAN_PHAM = sp,
                    NGUOI_DUNG = nd
                };

                _db.AddToDANH_GIA(dg);

                int num = sp.DANH_GIA.Count;

                float average = 0;

                foreach (var danhgia in sp.DANH_GIA)
                {
                    average += (float)danhgia.Diem / num;
                }

                sp.Diem = (short)average;

                _db.SaveChanges();
                sp.LOAI_SAN_PHAMReference.Load();

                return RedirectToAction("Details", sp.LOAI_SAN_PHAM.TenLoaiSanPham, new { id = id });
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Grade/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Grade/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
